using System;
using System.Xml;
using DesignPatternDefinitions;

namespace CodeGenerators
{
	internal class CPlusPlusProjectGenerator : DefaultProjectGenerator
	{
		private XmlDocument mDoc;
		private IProject mProject;
		
		public override string GenerateProjectFile(string directory, IProject project)
		{
			string projectRoot = base.GenerateProjectFile(directory,project);
			string fileName = projectRoot + "\\" + project.ProjectName + ".vcproj";
			string templatePath = System.Windows.Forms.Application.StartupPath + Constants.TEMPLATEPATH +"\\Template.vcproj";
			try
			{
				mProject = project;
				mDoc = new XmlDocument();
				mDoc.Load( templatePath );
				AddHeaderData();
				AddClasses();
				mDoc.Save( fileName );
			}
			catch
			{
			}
			return projectRoot;
		}

		private void AddHeaderData()
		{
			XmlElement root = mDoc.DocumentElement as XmlElement;
			root.Attributes["ProjectGUID"].Value = Guid.NewGuid().ToString("P");
			root.Attributes["Name"].Value = mProject.ProjectName;
		}
		private void AddClasses()
		{
			XmlElement files = mDoc.DocumentElement.SelectSingleNode("Files") as XmlElement;
			XmlElement srcfiles = files.SelectSingleNode( "./Filter[@Name='Source Files']" ) as XmlElement;
			XmlElement hfiles = files.SelectSingleNode( "./Filter[@Name='Header Files']" ) as XmlElement;
			foreach( IProjectComponent component in mProject.Components )
			{
				foreach( IClass cls in component.Classes )
				{
					XmlElement elem = mDoc.CreateElement( "File" );
					XmlAttribute rpath = mDoc.CreateAttribute("RelativePath");
					rpath.Value = component.ComponentName + "\\" + cls.ClassName + ".h";
					elem.Attributes.Append(rpath);
					hfiles.AppendChild( elem );

					elem = mDoc.CreateElement( "File" );
					rpath = mDoc.CreateAttribute("RelativePath");
					rpath.Value = component.ComponentName + "\\" + cls.ClassName + ".cpp";
					elem.Attributes.Append(rpath);
					srcfiles.AppendChild( elem );
				}
			}
		}
	}
}
